package com.jf.mall.utils;

import org.apache.commons.fileupload.FileItem;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-10-14
 * Time:11:32
 */
public class WebUtils {
    public static String saveFile(String dic, FileItem fileItem, HttpServletRequest req) throws Exception {
        String fileName = fileItem.getName();
        if (fileName == null || fileName.isEmpty()) return null;
        fileName = UUID.randomUUID() + "_" + fileName;
        String dicPath = dic + getYMD();
        String realDicPath = req.getServletContext().getRealPath(dicPath);
        File folder = new File(realDicPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String realFilePath = realDicPath + fileName;
        fileItem.write(new File(realFilePath));
        return dicPath + fileName;
    }

    public static boolean deleteFile(String filePath, HttpServletRequest req) throws Exception {
        String realPath = req.getServletContext().getRealPath(filePath);
        File file = new File(realPath);
        if (file.exists()) return file.delete();
        return false;
    }

    public static String getYMD() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd/");
        return time.format(dateTimeFormatter);
    }
}
